import datetime,cgi
import sys
import os
from google.appengine.ext.webapp import template
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.api import users
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.dist import use_library
from os import environ
from models import *

class ReviewProjectSubmission(webapp.RequestHandler):
	global projectid

	def post(self):
		global projectid
		is_confirm = self.request.get('confirm', None)
		is_reject = self.request.get('reject', None)
		details=[]
		projects=db.GqlQuery("SELECT * FROM projectDetails WHERE projectid='%s'" %projectid)
		for project in projects:
			teamid=project.teamid
			pname=project.projectname
			members=db.GqlQuery("SELECT * FROM teamDetails WHERE teamid='%s'" %teamid)
			mem=members
		if is_confirm:
			query="SELECT * FROM projectDetails WHERE projectid='%s'" %(projectid)
			confirmMe = db.GqlQuery(query)
			for project in confirmMe:
				note="Your project '%s' has been confirmed" %project.projectname
				project.confirmed=True
				project.put()
			for i in mem:
				listmembers=i.teammember
				members=listmembers.split(",")
				for member in members:
					newnote=notificationDetails(admissionnumber=member,notification=note)
					key=newnote.put()
					idnum=key.id()
					newnote.notificationid=str(idnum)
					newnote.put()
		elif is_reject:
			query="SELECT * FROM projectDetails WHERE projectid='%s'" %(projectid)
			deleteMe = db.GqlQuery(query)
			for project in deleteMe:
				note="Your project '%s' has been rejected" %project.projectname
				project.delete()
			for i in mem:
				listmembers=i.teammember
				members=listmembers.split(",")
				for member in members:
					newnote=notificationDetails(admissionnumber=member,notification=note)
					key=newnote.put()
					idnum=key.id()
					newnote.notificationid=str(idnum)
					newnote.put()
		else:
			raise Exception('no form action given')
		self.redirect("/reviewprojectmain")

	def verifyLogin(self):
		user = users.get_current_user()
		if user:
			usercheck=userDetails.all()
			usercheck.filter("email =",user.email())
			try:
				currentuser=usercheck.fetch(1)[0]
				userdet=db.GqlQuery("SELECT * FROM userDetails WHERE email='"+user.email()+"'")
				for i in userdet:
					if i.privilege=='admin':
						return
					elif i.approved==False:
						self.redirect("/usererror")
						return
				self.redirect("/user")
			except:
				path = os.path.join(os.path.dirname(__file__),'form.html')#use template
				self.response.out.write(template.render(path,{"email":user.email()}))#using template
		else:
			self.redirect(users.create_login_url(self.request.uri))

	def get(self):
		self.verifyLogin()
		global projectid
		projectid=''
		url = self.request.url
		for i in range(0,len(url),1):
			if(url[i]=='?'):
				i=i+1
				while(url[i]!='='):
					projectid=projectid+url[i]
					i=i+1
				break
		currentproject=db.GqlQuery("SELECT * FROM projectDetails WHERE projectid='%s'"%projectid)
		tmp=[]
		for project in currentproject:
			tmp1=[]
			tmp1.append(project.projectid)
			tmp1.append(project.projectname)
			tmp1.append(project.abstract)
			tmp1.append(project.languages)
			tmp1.append(project.category)
			tmp1.append(project.fieldnames)
			tmp.append(tmp1)
		path = os.path.join(os.path.dirname(__file__),'reviewproject.html')#use template
		self.response.out.write(template.render(path,{"review":tmp}))#using template

class ReviewProjectMain(webapp.RequestHandler):
	def verifyLogin(self):
		user = users.get_current_user()
		if user:
			usercheck=userDetails.all()
			usercheck.filter("email =",user.email())
			try:
				currentuser=usercheck.fetch(1)[0]
				userdet=db.GqlQuery("SELECT * FROM userDetails WHERE email='"+user.email()+"'")
				for i in userdet:
					if i.privilege=='admin':
						return
					elif i.approved==False:
						self.redirect("/usererror")
						return
				self.redirect("/user")
			except:
				path = os.path.join(os.path.dirname(__file__),'form.html')#use template
				self.response.out.write(template.render(path,{"email":user.email()}))#using template
		else:
			self.redirect(users.create_login_url(self.request.uri))

	def get(self):
		self.verifyLogin()
		notConfirmed=db.GqlQuery("SELECT * FROM projectDetails WHERE confirmed=False")
		path = os.path.join(os.path.dirname(__file__),'reviewprojectmain.html')#use template
		tmp=[]
		for project in notConfirmed:
			tmp1=[]
			tmp1.append(project.projectname)
			tmp1.append(project.projectid)
			tmp.append(tmp1)
		self.response.out.write(template.render(path,{"projects":tmp}))#using template

application = webapp.WSGIApplication([('/reviewprojectsubmission', ReviewProjectSubmission),('/reviewprojectmain', ReviewProjectMain)],debug=True)

def main():
	run_wsgi_app(application)

if __name__ == "__main__":
	main()
